package com.foreknow.controller;

import com.foreknow.model.GuestBook;
import com.foreknow.service.impl.GuestBookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AddMessageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //服务器端向客户端响应的内容的类型（MIME）
        resp.setContentType("text/html;charset=utf-8");
        //设置客户端向服务器端发送请求的字符编码集
        req.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        //获取请求参数
        GuestBook gb = new GuestBook();
        String name = req.getParameter("name");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        //创建时间
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String createdTime = sdf.format(date);//将日期类型转换为指定格式的字符串


        gb.setName(name);
        gb.setPhone(phone);
        gb.setEmail(email);
        gb.setTitle(title);
        gb.setContent(content);
        gb.setCreatedTime(createdTime);
        //调用service的add方法
        GuestBookServiceImpl guestBookService = new GuestBookServiceImpl();
        boolean isRight = guestBookService.gSave(gb);
        //判断添加成功还是失败
        if (isRight){
            //转发资源（请求转发）
            //req.getRequestDispatcher("/ShowMessageServlet").forward(req,resp);

            //重定向
            resp.sendRedirect(req.getContextPath()+"/ManagerServlet");

//            ShowMessageServlet show = new ShowMessageServlet();
//            show.doGet(req,resp);
            //out.println("<a href='ShowMessageServlet'>查看所有留言信息</a>");
        }else {
            out.println("添加失败！");
        }
    }
}
